#include "Bind_Operation.h"


Bind_Operation::Bind_Operation(void)
{
	
}



Bind_Operation::~Bind_Operation(void)
{
	if(User_name!=0)
		delete[] User_name;
	if(password!=0)
		delete[] password;
}



//functia buna de bind
Bind_Operation::Bind_Operation(char *dn,vector<Atribut<char*>> atribute)
					:LDAP_Operation(dn,atribute)
{
	User_name = 0;
	password = 0;
	type_only = true;

	for(int i=0 ; i<atribute.size();i++)
	{
		if(!strcmp(atribute[i].daNume(),"cn"))
			this->setUser(atribute[i].daAtribut());
		else
			if(!strcmp(atribute[i].daNume(),"sn") || !strcmp(atribute[i].daNume(),"description"))
				this->setPassword(atribute[i].daAtribut());
	}
}


Bind_Operation::Bind_Operation(const Bind_Operation& bind_op):LDAP_Operation(bind_op)
{
	User_name = new char[strlen(bind_op.User_name)+1];
	password=new char[strlen(bind_op.password)+1];
	
	if(User_name==0 || password==0 )
		throw new exception();

	strcpy(User_name,bind_op.User_name);
	strcpy(password,bind_op.password);
	
}

Bind_Operation& Bind_Operation::operator=(const Bind_Operation& bind_op)
{
	throw new exception();
	//!!!Mecanism de apelare a operatorului=potrivit

	if(this!=&bind_op)
	{
		if(User_name!=0)
			delete[] User_name;
		if(password!=0)
			delete[] password;
		
		
		User_name=new char[strlen(bind_op.User_name)+1];
		password=new char[strlen(bind_op.password)+1];
		
		if(User_name==0 || password==0 )
			throw new exception();
		strcpy(User_name,bind_op.User_name);
		strcpy(password,bind_op.password);
	}
	return (*this);
}

LDAP_Operation* Bind_Operation::operate()
{
		//formatarea result pentru entryldapsearch -x -LLL -b dc=tup,dc=com cn=user1
	result=new char[1000];
	strcpy(result,"ldapsearch ");

	switch(this->auth_type)
	{
	case 0: strcat(result,"-x ");
		break;
	case 1: strcat(result," ");
		break;
	default: printf("\nExceptie:");
		//exceptie;
	}

	for(int i=0;i<nr_opt;i++)
	{
		strcat(result,option[i]);
		strcat(result," ");
	}

	
	if(this->type_only)
		strcat(result,"-b ");

	//adaugarea dn-ului

	if(strlen(this->DN))
		strcat(result,this->DN);
	strcat(result," ");

	// adaugarea atributului...numele utilizatorului

	strcat(result,atribute[0].daNume());
	strcat(result,"=");
	strcat(result,atribute[0].daAtribut());

	strcat(result,"*");

	LDAP_Operation *op=new Bind_Operation((*this));
	//!!!!!!!! SMART POINTERI PT A LUCRA CU CEEA CE RETURNEZI
	return op;
}

void Bind_Operation::setUser(char *username)
{
	if(User_name!=0)
		delete[] User_name;

	User_name = new char[strlen(username)+1];
	if(User_name == 0)
		throw new exception();

	strcpy(User_name,username);
}

void Bind_Operation::setPassword(char *pass)
{
	if(password!=0)
		delete[] password;
	password=new char[strlen(pass)+1];
	if(password==0)
		throw new exception();
	strcpy(password,pass);
}

